///被观察者
class Subject {
  late List<Observer> _observers;

  ///传入观察者列表
  Subject([List<Observer>? observers]) {
    _observers = observers ?? [];
  }

  ///注册观察者
  void registerObserver(Observer observer) {
    _observers.add(observer);
  }

  ///注销观察者
  void unregisterObserver(Observer observer) {
    _observers.remove(observer);
  }

  ///通知观察者
  void notifyObservers(Notification notification) {
    for (var observer in _observers) {
      observer.notify(notification);
    }
  }
}

///观察者类
class Observer {
  String name;

  Observer(this.name);

  void notify(Notification notification) {
    print(
        "[${notification.timestamp.toIso8601String()}] Hey $name, ${notification.message}!");
  }
}

///通知
class Notification {
  late DateTime timestamp;
  late String message;

  Notification.forNow(String name) {
    timestamp = DateTime.now();
    message = "msg: $name";
  }
}

///创建一个业务类CoffeeMaker继承被观察者类Subject
class CoffeeMaker extends Subject {
  CoffeeMaker([List<Observer>? observers]) : super(observers);

  void brew() {
    print("Brewing the coffee...");
    notifyObservers(Notification.forNow("coffee's done"));
  }
}

void main() {
  ///创建观察者
  var me = Observer("Tyler");
  ///初始化观察者列表
  var mrCoffee = CoffeeMaker(List.from([me]));
  ///创建观察者
  var myWife = Observer("Kate");
  ///注册观察者
  mrCoffee.registerObserver(myWife);
  ///通知观察者
  mrCoffee.brew();
}
